<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-6xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Presentation API</h1>
        <p class="text-gray-300 text-lg">
          将内容投影到外部显示器、投影仪或无线显示设备
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300 mb-4">
          您的浏览器不支持 Presentation API。此功能需要 Chrome 47+, Edge 79+ 或其他支持该 API 的浏览器。
        </p>
        <p class="text-gray-400 text-sm">
          注意：需要连接外部显示设备或使用 Chrome Cast、Miracast 等无线显示技术。
        </p>
      </div>

      <!-- 演示控制 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">演示控制</h2>
        
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <div class="bg-gray-800 rounded-lg p-4">
            <div class="text-gray-400 text-sm mb-1">连接状态</div>
            <div class="text-white text-xl font-semibold">
              {{ connectionState }}
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-4">
            <div class="text-gray-400 text-sm mb-1">演示 ID</div>
            <div class="text-white text-lg font-semibold truncate" :title="presentationId">
              {{ presentationId || '-' }}
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-4">
            <div class="text-gray-400 text-sm mb-1">消息计数</div>
            <div class="text-white text-xl font-semibold">
              {{ messageCount }}
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-4">
            <div class="text-gray-400 text-sm mb-1">可用性</div>
            <div class="text-white text-xl font-semibold">
              {{ availability || '未知' }}
            </div>
          </div>
        </div>

        <div class="flex gap-3">
          <button
            v-if="!connection"
            @click="startPresentation"
            :disabled="!isSupported || availability === 'unavailable'"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-presentation-file mr-2"></i>
            开始演示
          </button>
          
          <button
            v-if="connection"
            @click="terminatePresentation"
            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-close mr-2"></i>
            终止演示
          </button>

          <button
            v-if="connection"
            @click="reconnectPresentation"
            class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-renew mr-2"></i>
            重新连接
          </button>
        </div>
      </div>

      <!-- 演示内容选择 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">演示内容</h2>
        <p class="text-gray-300 mb-6">选择要在外部显示器上展示的内容</p>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <button
            @click="selectPresentation('slides')"
            :class="selectedPresentation === 'slides' ? 'border-tech-accent' : 'border-gray-700'"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left border-2"
          >
            <i class="i-carbon-presentation-file text-3xl text-blue-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">幻灯片</div>
            <div class="text-gray-400 text-sm">专业演示幻灯片</div>
          </button>

          <button
            @click="selectPresentation('video')"
            :class="selectedPresentation === 'video' ? 'border-tech-accent' : 'border-gray-700'"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left border-2"
          >
            <i class="i-carbon-video text-3xl text-green-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">视频播放</div>
            <div class="text-gray-400 text-sm">全屏视频展示</div>
          </button>

          <button
            @click="selectPresentation('dashboard')"
            :class="selectedPresentation === 'dashboard' ? 'border-tech-accent' : 'border-gray-700'"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left border-2"
          >
            <i class="i-carbon-dashboard text-3xl text-yellow-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">数据仪表板</div>
            <div class="text-gray-400 text-sm">实时数据监控</div>
          </button>

          <button
            @click="selectPresentation('gallery')"
            :class="selectedPresentation === 'gallery' ? 'border-tech-accent' : 'border-gray-700'"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left border-2"
          >
            <i class="i-carbon-image text-3xl text-purple-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">图片画廊</div>
            <div class="text-gray-400 text-sm">照片幻灯片</div>
          </button>

          <button
            @click="selectPresentation('code')"
            :class="selectedPresentation === 'code' ? 'border-tech-accent' : 'border-gray-700'"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left border-2"
          >
            <i class="i-carbon-code text-3xl text-orange-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">代码演示</div>
            <div class="text-gray-400 text-sm">代码编辑器</div>
          </button>

          <button
            @click="selectPresentation('custom')"
            :class="selectedPresentation === 'custom' ? 'border-tech-accent' : 'border-gray-700'"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left border-2"
          >
            <i class="i-carbon-document-blank text-3xl text-red-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">自定义内容</div>
            <div class="text-gray-400 text-sm">HTML 自定义</div>
          </button>
        </div>
      </div>

      <!-- 消息通信 -->
      <div v-if="connection" class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">消息通信</h2>
        
        <div class="bg-gray-800 rounded-lg p-6 mb-6">
          <h3 class="text-white font-semibold mb-4">发送消息到演示屏幕</h3>
          
          <div class="space-y-4">
            <div>
              <label class="text-white font-medium mb-2 block">消息内容</label>
              <input
                v-model="messageToSend"
                type="text"
                placeholder="输入要发送的消息"
                @keyup.enter="sendMessage"
                class="w-full bg-gray-700 text-white px-4 py-3 rounded-lg border border-gray-600 focus:border-tech-accent outline-none"
              >
            </div>

            <div class="flex gap-3">
              <button
                @click="sendMessage"
                :disabled="!messageToSend"
                class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
              >
                <i class="i-carbon-send mr-2"></i>
                发送消息
              </button>

              <button
                @click="sendCommand('next')"
                class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors"
              >
                <i class="i-carbon-chevron-right mr-2"></i>
                下一页
              </button>

              <button
                @click="sendCommand('prev')"
                class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-3 rounded-lg transition-colors"
              >
                <i class="i-carbon-chevron-left mr-2"></i>
                上一页
              </button>
            </div>
          </div>
        </div>

        <!-- 接收的消息 -->
        <div class="bg-gray-800 rounded-lg p-6">
          <h3 class="text-white font-semibold mb-4">来自演示屏幕的消息</h3>
          
          <div v-if="receivedMessages.length === 0" class="text-gray-400 text-center py-4">
            暂无接收的消息
          </div>

          <div v-else class="space-y-2 max-h-64 overflow-y-auto">
            <div
              v-for="(msg, index) in receivedMessages.slice().reverse()"
              :key="index"
              class="bg-gray-700 rounded-lg p-3"
            >
              <div class="text-white">{{ msg.content }}</div>
              <div class="text-gray-400 text-xs mt-1">{{ msg.timestamp }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 设备检测 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">可用设备</h2>
        
        <div class="bg-gray-800 rounded-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="text-white">
              检测可用的演示显示设备
            </div>
            <button
              @click="checkAvailability"
              class="text-tech-accent hover:text-tech-accent/80 transition-colors"
            >
              <i class="i-carbon-renew mr-1"></i>
              刷新
            </button>
          </div>

          <div class="space-y-3">
            <div class="flex items-center">
              <i
                :class="availability === 'available' ? 'i-carbon-checkmark-filled text-green-400' : 'i-carbon-close-filled text-red-400'"
                class="text-xl mr-3"
              ></i>
              <div>
                <div class="text-white">演示设备</div>
                <div class="text-gray-400 text-sm">
                  {{ availabilityText }}
                </div>
              </div>
            </div>

            <div class="text-gray-400 text-sm mt-4">
              <strong class="text-white">支持的设备：</strong>
              <ul class="list-disc list-inside mt-2 space-y-1">
                <li>外接显示器和投影仪</li>
                <li>Google Chromecast</li>
                <li>支持 Miracast 的设备</li>
                <li>支持 AirPlay 的设备（部分浏览器）</li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      <!-- 事件日志 -->
      <div v-if="logs.length > 0" class="tech-card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-semibold text-white">事件日志</h2>
          <button
            @click="clearLogs"
            class="text-red-400 hover:text-red-300 text-sm"
          >
            <i class="i-carbon-clean mr-1"></i>
            清空日志
          </button>
        </div>

        <div class="space-y-2 max-h-64 overflow-y-auto">
          <div
            v-for="(log, index) in logs.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-3 flex items-start text-sm"
          >
            <i
              :class="getLogIcon(log.type)"
              class="text-lg mr-3 mt-0.5"
            ></i>
            <div class="flex-1">
              <div class="text-white">{{ log.message }}</div>
              <div class="text-gray-400 text-xs mt-1">{{ log.timestamp }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 47+, Edge 79+, Opera 34+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要接口</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">PresentationRequest</code> - 创建演示请求</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">PresentationConnection</code> - 演示连接</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">PresentationAvailability</code> - 检测可用性</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">start()</code> - 开始演示</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">reconnect()</code> - 重新连接</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">terminate()</code> - 终止演示</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">连接状态</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">connecting</code> - 正在连接</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">connected</code> - 已连接</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">closed</code> - 已关闭</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">terminated</code> - 已终止</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">消息通信</h4>
            <p class="text-sm leading-relaxed mb-2">
              控制端和演示端之间可以双向通信。控制端可以发送命令（如切换幻灯片），
              演示端可以发送状态更新（如当前页码）。
            </p>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>使用 <code class="bg-gray-800 px-1 rounded">send()</code> 发送消息</li>
              <li>监听 <code class="bg-gray-800 px-1 rounded">message</code> 事件接收消息</li>
              <li>支持文本和二进制数据</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>会议演示和幻灯片放映</li>
              <li>教育培训和在线课程</li>
              <li>数字标牌和信息展示</li>
              <li>多屏幕游戏体验</li>
              <li>媒体播放和流媒体</li>
              <li>协作工作和远程展示</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">工作流程</h4>
            <ol class="list-decimal list-inside space-y-1 text-sm">
              <li>创建 PresentationRequest 指定演示 URL</li>
              <li>检查可用的演示显示设备</li>
              <li>调用 start() 开始演示并选择设备</li>
              <li>建立 PresentationConnection</li>
              <li>控制端和演示端通过消息通信</li>
              <li>可以重新连接或终止演示</li>
            </ol>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">安全要求</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>需要 HTTPS 或 localhost 环境</li>
              <li>需要用户手势触发（如点击按钮）</li>
              <li>演示 URL 必须与控制页面同源或配置 CORS</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">注意事项</h4>
            <ul class="list-disc list-inside space-y-1 text-sm text-yellow-400">
              <li>⚠️ 需要实际的外部显示设备或 Cast 设备</li>
              <li>⚠️ 开发时可以使用 Chrome 的远程调试功能测试</li>
              <li>⚠️ 演示页面需要单独创建和托管</li>
              <li>⚠️ 不同设备可能有不同的显示限制</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'

// 类型定义
interface Log {
  type: 'info' | 'success' | 'warning' | 'error'
  message: string
  timestamp: string
}

interface Message {
  content: string
  timestamp: string
}

// 响应式状态
const isSupported = ref('PresentationRequest' in window)
const connection = ref<any>(null)
const presentationId = ref('')
const messageCount = ref(0)
const availability = ref<string>('')
const selectedPresentation = ref('slides')

const messageToSend = ref('')
const receivedMessages = ref<Message[]>([])
const logs = ref<Log[]>([])

let presentationRequest: any = null
let availabilityObj: any = null

// 计算属性
const connectionState = computed(() => {
  if (!connection.value) return '未连接'
  return connection.value.state || '未知'
})

const availabilityText = computed(() => {
  if (availability.value === 'available') return '检测到可用的演示设备'
  if (availability.value === 'unavailable') return '未检测到演示设备'
  return '正在检测...'
})

// 初始化
onMounted(() => {
  if (isSupported.value) {
    initPresentationRequest()
    checkAvailability()
  }
})

// 清理
onUnmounted(() => {
  if (connection.value) {
    try {
      connection.value.close()
    } catch (err) {
      console.error('关闭连接失败:', err)
    }
  }
})

// 初始化演示请求
const initPresentationRequest = () => {
  try {
    // 创建演示 URL（这里使用当前页面作为演示内容）
    const presentationUrl = window.location.origin + '/presentation.html'
    
    presentationRequest = new (window as any).PresentationRequest(presentationUrl)
    
    addLog('success', 'Presentation Request 初始化成功')
  } catch (err) {
    console.error('初始化失败:', err)
    addLog('error', '初始化失败')
  }
}

// 检查可用性
const checkAvailability = async () => {
  if (!presentationRequest) return

  try {
    addLog('info', '正在检测演示设备...')
    
    availabilityObj = await presentationRequest.getAvailability()
    availability.value = availabilityObj.value ? 'available' : 'unavailable'
    
    availabilityObj.addEventListener('change', () => {
      availability.value = availabilityObj.value ? 'available' : 'unavailable'
      addLog('info', `设备可用性变更: ${availability.value}`)
    })
    
    addLog('info', `设备可用性: ${availability.value}`)
  } catch (err) {
    console.error('检测可用性失败:', err)
    addLog('warning', '无法检测设备可用性')
    availability.value = 'unavailable'
  }
}

// 选择演示内容
const selectPresentation = (type: string) => {
  selectedPresentation.value = type
  addLog('info', `选择演示内容: ${type}`)
}

// 开始演示
const startPresentation = async () => {
  if (!presentationRequest) {
    addLog('error', '演示请求未初始化')
    return
  }

  try {
    addLog('info', '正在启动演示...')
    
    // 开始演示
    connection.value = await presentationRequest.start()
    presentationId.value = connection.value.id
    
    // 设置事件监听
    setupConnectionListeners()
    
    addLog('success', '演示已启动')
    addLog('info', `演示 ID: ${presentationId.value}`)
    
  } catch (err) {
    console.error('启动演示失败:', err)
    
    if (err instanceof Error) {
      if (err.name === 'NotFoundError') {
        addLog('error', '未找到可用的演示设备')
      } else if (err.name === 'NotAllowedError') {
        addLog('error', '用户取消了演示')
      } else {
        addLog('error', `启动失败: ${err.message}`)
      }
    } else {
      addLog('error', '启动演示失败')
    }
  }
}

// 设置连接监听器
const setupConnectionListeners = () => {
  if (!connection.value) return

  // 连接状态变化
  connection.value.addEventListener('connect', () => {
    addLog('success', '演示连接已建立')
  })

  connection.value.addEventListener('close', () => {
    addLog('info', '演示连接已关闭')
    connection.value = null
    presentationId.value = ''
  })

  connection.value.addEventListener('terminate', () => {
    addLog('info', '演示已终止')
    connection.value = null
    presentationId.value = ''
  })

  // 接收消息
  connection.value.addEventListener('message', (event: MessageEvent) => {
    const message = event.data
    receivedMessages.value.push({
      content: message,
      timestamp: new Date().toLocaleTimeString('zh-CN')
    })
    messageCount.value++
    addLog('info', `收到消息: ${message}`)
  })
}

// 发送消息
const sendMessage = () => {
  if (!connection.value || !messageToSend.value) return

  try {
    connection.value.send(messageToSend.value)
    addLog('success', `发送消息: ${messageToSend.value}`)
    messageToSend.value = ''
    messageCount.value++
  } catch (err) {
    console.error('发送消息失败:', err)
    addLog('error', '发送消息失败')
  }
}

// 发送命令
const sendCommand = (command: string) => {
  if (!connection.value) return

  try {
    const commandData = JSON.stringify({ command, type: selectedPresentation.value })
    connection.value.send(commandData)
    addLog('success', `发送命令: ${command}`)
    messageCount.value++
  } catch (err) {
    console.error('发送命令失败:', err)
    addLog('error', '发送命令失败')
  }
}

// 重新连接
const reconnectPresentation = async () => {
  if (!presentationRequest || !presentationId.value) return

  try {
    addLog('info', '正在重新连接...')
    
    connection.value = await presentationRequest.reconnect(presentationId.value)
    setupConnectionListeners()
    
    addLog('success', '重新连接成功')
  } catch (err) {
    console.error('重新连接失败:', err)
    addLog('error', '重新连接失败')
  }
}

// 终止演示
const terminatePresentation = () => {
  if (!connection.value) return

  try {
    connection.value.terminate()
    addLog('success', '演示已终止')
  } catch (err) {
    console.error('终止演示失败:', err)
    addLog('error', '终止演示失败')
  }
}

// 添加日志
const addLog = (type: 'info' | 'success' | 'warning' | 'error', message: string) => {
  logs.value.push({
    type,
    message,
    timestamp: new Date().toLocaleTimeString('zh-CN')
  })

  // 只保留最近 50 条
  if (logs.value.length > 50) {
    logs.value.shift()
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 获取日志图标
const getLogIcon = (type: string) => {
  const icons = {
    info: 'i-carbon-information-filled text-blue-400',
    success: 'i-carbon-checkmark-filled text-green-400',
    warning: 'i-carbon-warning-filled text-yellow-400',
    error: 'i-carbon-error-filled text-red-400'
  }
  return icons[type as keyof typeof icons]
}
</script>

